package com.jcl.recruit.core.web.filter;

import com.jcl.core.security.RequestStatus;
import com.jcl.core.security.SecurityUtils;
import com.jcl.core.security.UserToken;
import com.jcl.recruit.core.web.context.CurrentThreadContext;
import com.jcl.recruit.core.web.utils.FilterUtils;
import com.jcl.recruit.core.web.utils.RequestConstants;
import com.jcl.recruit.core.utils.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName RequestSecurityFilter
 * @Description TODO
 * @Author yyliu
 * @Date 2018/9/5 13:49
 * @Version 1.0
 **/
public class RequestSecurityFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestSecurityFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        FilterUtils.printRequest(this, req);

        // cors setting
        corsSetting(req, resp);


        // 安全请求
        if(FilterUtils.isSecurityUrl(req)){
            chain.doFilter(req, resp);
            return;
        }

        // 爬虫 过滤
        if(FilterUtils.isCrawlerUrl(req)){
            chain.doFilter(req, resp);
            return;
        }

        // 爬虫 过滤
        if(FilterUtils.unsetUrl(req)){
            chain.doFilter(req, resp);
            return;
        }


        UserToken userToken = isSecurityRequest(req, resp);
        if(null == userToken){
            return;
        }

        //UserToken userToken = testSecurityRequest(req);
        // 判断是否有效
        // 。。。
        String corpCode = "";
        String userId = "";
        if(null != userToken){
            if(null != userToken.getCorpCode()){
                corpCode = userToken.getCorpCode();
            }
            if(null != userToken.getUserId()){
                userId = userToken.getUserId();
            }
        }
        req.getSession().setAttribute(RequestConstants.ATTR_CORP_CODE_KEY, corpCode);
        req.getSession().setAttribute(RequestConstants.ATTR_USER_ID_KEY, userId);
        CurrentThreadContext.setAlias(corpCode);

        chain.doFilter(req, resp);
    }

    public UserToken isSecurityRequest(HttpServletRequest req, HttpServletResponse resp){

        String token = req.getHeader(RequestConstants.ATTR_TOKEN_KEY);
        //logger.info("request header token is : {}", token);
        if (null == token) {
            token = req.getParameter("token");
        }
        if(null == token){
            SecurityUtil.outputError(resp, RequestStatus.REQUEST_PARAM_CODE);
            return null;
        }
        UserToken userToken = null;
        try{
            userToken = SecurityUtils.decodeUserToken(token);
        }catch (Exception e){
            SecurityUtil.outputError(resp, RequestStatus.REQUEST_ILLEGAL_CODE);
            return null;
        }

        if(null == userToken){
            SecurityUtil.outputError(resp, RequestStatus.REQUEST_ILLEGAL_CODE);
            return null;
        }

        return userToken;
    }

    public UserToken testSecurityRequest(HttpServletRequest req){
        String token = req.getHeader(RequestConstants.ATTR_TOKEN_KEY);
        if (null == token) {
            token = req.getParameter("token");
        }
        UserToken userToken = null;
        if(null != token){
            try{
                userToken = SecurityUtils.decodeUserToken(token);
            }catch (Exception e){

            }
        }
        return userToken;
    } 

    public void corsSetting(HttpServletRequest req, HttpServletResponse resp){
        // resp.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        resp.setHeader("Access-Control-Max-Age","3600");
        resp.setHeader("Access-Control-Allow-Headers","x-requested-with,Cache-Control,Pragma,Content-Type,Token,TOKEN");
        resp.setHeader("Access-Control-Allow-Credentials","true");
    }

    @Override
    public void destroy() {

    }
}
